var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

//express-jwt：用来验证token是否有效的中间件
var jwt=require("express-jwt");
var token=require("./util/token");
var cors=require("cors");

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var newsRouter=require("./routes/news");
var commentsRouter=require("./routes/comments");
var adminRouter=require("./routes/admin");
var adminMangerRouter=require("./routes/aManger");

var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/news',newsRouter);
app.use('/comments',commentsRouter);
app.use("/admin",adminRouter);
app.use("/aManger",adminMangerRouter);

/**使用express-jwt中间件,查看express-jwt的版本号，npm list express-jwt
 * 7以下的版本调用jwt(),7以上的版本调用jwt.expressjwt()
 */
app.use(jwt.expressjwt({
  secret:"jwt_token_secret",//token密钥
  algorithms:["HS256"] //数字签名算法，默认HS256
}).unless(     //白名单:不需要验证token就可以访问的路由
  {
     path:["/users/login","/","/users/regist",/^\/news\//]
  }
));


//定义拦截器，验证token是否有效
app.use((req,res,next)=>{
   //客户端在得到服务器签发的token后，每一次请求都要手动将token添加到请求报文头的authorization字段中。
   //获取请求报文头部的token
   let t=req.headers["authorization"];
   if(t){
       //解析token   
       token.getToken(t).then((data)=>{
          req.data=data;
          return next();
       }).catch((err)=>{
          return next();
       }); 
   }else{
       return next();
   }
});



//错误中间件，在token失效时返回信息
app.use((err,req,res,next)=>{
     if(err.status==401){
        res.send({code:401,msg:"token失效",data:{}});
     }
});


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
